package com.yang.sso.oauth.oauth.exception;

import com.yang.sso.oauth.result.Result;
import com.yang.sso.oauth.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;


import javax.servlet.http.HttpServletRequest;

/**
 * @author lslands
 */


@Component
@Slf4j
public class AuthExceptionHandler {

    @Autowired
    private HttpServletRequest request;

    /**
     * 用户名不存在
     * @param e
     * @return
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public Result<?> exceptionHandler(UsernameNotFoundException e) {
        log.warn("异常类型:{};请求地址:{};方式:{};参数:{};异常原因:{}","UsernameNotFoundException",
                request.getRequestURI(),request.getMethod(),
                request.getQueryString(),e.getMessage());
        return Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
    }

    /**
     * 认证失败
     * @param e
     * @return
     */
    @ExceptionHandler(InvalidGrantException.class)
    public Result<?> exceptionHandler(InvalidGrantException e) {
        log.warn("异常类型:{};异常原因:{}","InvalidGrantException",
                request.getRequestURI(),request.getMethod(),
                request.getQueryString(),e.getMessage());
        return Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
    }


    /**
     * 账户异常(禁用、锁定、过期)
     * @param e
     * @return
     */
    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public Result<?> exceptionHandler(InternalAuthenticationServiceException e) {
        log.warn("异常类型:{};异常原因:{}","InvalidGrantException",e.getMessage());
        return Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
    }



    /**
     * token 无效或已过期
     * @param e
     * @return
     */
    @ExceptionHandler(InvalidTokenException.class)
    public Result<?> exceptionHandler(InvalidTokenException e) {
        log.warn("异常类型:{};异常原因:{}","InvalidGrantException",e.getMessage());
        return Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
    }

}
